package com.kusiri.kframework.salesforce.ui
{
	import com.kusiri.kframework.salesforce.model.SObject;
	import com.salesforce.results.DescribeLayoutResult;
	
	import mx.containers.VBox;
	import mx.controls.Alert;
			
	public class SObjectDisplay extends VBox
	{
		
		/**
		 * link back into the model
		 */
		[Bindable]
		public var sobject:SObject;

		[Bindable]
		public var editable:Boolean;
					
		public var onSave:Function;
		public var onCancel:Function;
		public var fields:Array;
		public var form:SObjectForm;
		public var buttonsOnly : Boolean = false;
		public var buttonsClass : Class;
		public var buttonsProperties : Object;
		public var layout:DescribeLayoutResult;
		
		public var inited:Boolean = false;
		
		public function SObjectDisplay()
		{
			this.percentWidth = 100;
		}

		// only build the form when necessary
		public function init() : void
		{
			if (inited) return;
			inited = true;
			
			sobject.__ensureFullyLoaded(
				function() : void
				{
					sobject.__describeLayout(
						function(o:DescribeLayoutResult) : void
						{
							layout = o;
							addForm();
							
						}, 
						function(o:*) : void
						{
							Alert.show('Could not load layout information from Salesforce');
						}
					);
				},
				function() : void 
				{
					Alert.show('Unable to load data');
				}
			);
					
		}
		
		private function addForm() : void
		{

			if (form) return;

			form = new SObjectForm(layout, sobject, onSave, onCancel, buttonsClass, buttonsProperties, buttonsOnly, editable);
			
			addChild(form);			
			
			
			
		}
		
	}
}